package com.jiafan.xcwncw.wxapi;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;

import com.android.volley.Request;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.work.game.R;
import com.work.game.config.UrlConfig;
import com.work.game.home.ui.activity.SplashGmActivity;
import com.work.game.home.ui.activity.WebViewActivity;
import com.work.game.home.ui.enums.RedisEnum;
import com.work.game.home.ui.model.User;
import com.work.game.home.ui.model.vo.RegisterVo;
import com.work.game.utils.risk.DeviceUtils;
import com.work.game.volley.BaseActivity;
import com.work.game.volley.state.HUCState;

import org.json.JSONException;
import org.json.JSONObject;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {
    public static String TAG = "MainActivity";

    private CheckBox checkBox;

    //微信授权登录
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        super.initView();
        checkBox = findViewById(R.id.cb_ok);
    }

    @Override
    public void initClick() {
        findViewById(R.id.tv_user_agreement).setOnClickListener(this);
        findViewById(R.id.tv_privacy_policy).setOnClickListener(this);
        findViewById(R.id.but_login).setOnClickListener(this);
    }

    @Override
    public void initUtils() {
        super.initUtils();
        String wxAppId = getSharedPreferences(RedisEnum.WX_LOGIN_APP_ID.getKey());
        String wxAppIdSecret = getSharedPreferences(RedisEnum.WX_LOGIN_APP_SECRET.getKey());
        if (StrUtil.isNotEmpty(wxAppId) && StrUtil.isNotEmpty(wxAppIdSecret)) {
            //给IWXAPI赋值，第二个参数是AppID
            api = WXAPIFactory.createWXAPI(this, wxAppId, false);
            //注册到微信，参数是AppID
            api.registerApp(wxAppId);

            //这个必须加上，否则回调显示会出问题
            api.handleIntent(getIntent(), this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_user_agreement:
                sendIntent(this, WebViewActivity.class,"用户协议");
                break;
            case R.id.tv_privacy_policy:
                sendIntent(this, WebViewActivity.class,"隐私政策");
                break;
            case R.id.but_login:
                if (!checkBox.isChecked()) {
                    showToast("请已读并同意《用户协议》和《隐私政策》");
                    return;
                }
                String wxAppId = getSharedPreferences(RedisEnum.WX_LOGIN_APP_ID.getKey());
                String wxAppIdSecret = getSharedPreferences(RedisEnum.WX_LOGIN_APP_SECRET.getKey());
                if (StrUtil.isNotEmpty(wxAppId) && StrUtil.isNotEmpty(wxAppIdSecret)) {
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = wxAppId;
                    api.sendReq(req);
                } else {
                    login(RedisEnum.WX_LOGIN_APP_ID.getKey());
                }
                login(RedisEnum.WX_LOGIN_APP_ID.getKey());
                break;
            default:
        }
    }


    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                loadDismiss();
                if (!(response instanceof User)) {
                    showToast(response.toString());
                    return;
                }
                User users = (User) response;
                setSharedPreferences("deviceId", users.getOpenid() + users.getDeviceId());
                setSharedPreferences("loginTime", users.getLoginTime());
                setSharedPreferences("usParentId", users.getUsParentId());
                setSharedPreferences("id", users.getId());
                setSharedPreferences("signInNumber", users.getSignInNumber());
                setSharedPreferences("signIdDayNumber", users.getSignIdDayNumber());
                setSharedPreferences("afbPhone", users.getAfbPhone());
                setSharedPreferences("afbName", users.getAfbName());
                setSharedPreferences("code", users.getCode());
                setSharedPreferences("moneyRedPacket", users.getMoneyRedPacket());
                setSharedPreferences("moneyGoldCoin", users.getMoneyGoldCoin());
                setSharedPreferences("nickname", users.getNickname());
                String index = getSharedPreferences("currentSubject");
                setSharedPreferences("currentSubject", StrUtil.isNotEmpty(index) ? index : "0");
                String answerCount = getSharedPreferences("currentSubject");
                setSharedPreferences("answerCount", StrUtil.isNotEmpty(answerCount) ? answerCount : "0");
                setSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS.getKey(), users.getRisk_advertising_coins());
                setSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS_THAN_EQUAL.getKey(), users.getRisk_advertising_coins_than_equal());
                setSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS_THAN_EQUAL_TWO.getKey(), users.getRisk_advertising_coins_than_equal_two());
                setSharedPreferences(RedisEnum.RISK_WHITE_LIST.getKey(), users.getRisk_white_list());
                sendIntent(this, SplashGmActivity.class);
                finish();
                break;
        }
    }

    /**
     * 获取剪切板的内容
     *
     * @return
     */
    private String getClipboard() {
        // 获取剪切板管理器
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

        // 检查剪切板是否有内容
        if (clipboard.hasPrimaryClip()) {
            ClipData clip = clipboard.getPrimaryClip();
            // 获取剪切板中第一项的内容
            if (clip != null && clip.getItemCount() > 0) {
                CharSequence text = clip.getItemAt(0).getText();
                if (text != null) {
                    // 这里你有了剪切板的文本内容
                    String clipboardContent = text.toString();
                    if (TextUtils.isEmpty(clipboardContent)) {
                        return null;
                    }
                    try {
                        JSONObject jsonObject = new JSONObject(clipboardContent);
                        return jsonObject.getString("pid");
                    } catch (JSONException e) {
                        return null;
                    }
                }
            }
        }
        return null;
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    public void onReq(BaseReq baseReq) {
        System.out.println("Code值=" + JSONUtil.toJsonStr(baseReq));
    }

    @Override
    public void onResp(BaseResp baseResp) {
        Log.i(TAG, "Code值=" + JSONUtil.toJsonStr(baseResp));
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK: //点击确定登录
                String code = JSONUtil.parseObj(JSONUtil.toJsonStr(baseResp)).getStr("code");
                login(code);
                break;
            default:
                //点击的取消，根据自身业务处理
                break;
        }
    }

    private void login(String wxCode) {
        //获取网络数据
        RegisterVo registerVo = new RegisterVo();
        String oaid = DeviceUtils.getInstance().getOaId(this);
        registerVo.setOaid(oaid);
        registerVo.setWxCode(wxCode);
        registerVo.setDeviceId(getMyUUID());
        String code = getClipboard();
        registerVo.setCode(code);
        Long firstInstallTime = DeviceUtils.getInstance().getLastLoginTimeByPackageName(this, "com.tencent.mm");
        registerVo.setFirstInstallTime(String.valueOf(firstInstallTime));
        String url =  UrlConfig.LOGIN_URL2;
        if (wxCode.equals(RedisEnum.WX_LOGIN_APP_ID.getKey())){
            url = UrlConfig.LOGIN_URL;
        }
        hucRequestInterfase.executeStr(this, User.class, HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, url, hucParameInterfase.getRequestParameter(registerVo), true);
        loading();
    }


    private String getMyUUID() {
        final String androidId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
        return androidId;
    }

}
